package com.guojian.common.http;

import java.io.IOException;
import java.lang.reflect.Type;
import java.util.List;

import org.apache.http.ParseException;
import org.apache.http.client.methods.CloseableHttpResponse;
import org.apache.http.util.EntityUtils;

import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.TypeReference;
import com.google.common.base.Charsets;
import com.guojian.common.utils.Assert;

import lombok.Data;

@Data
public class Response {

	private CloseableHttpResponse response;

	public Response(CloseableHttpResponse response) {
		super();
		this.response = response;
	}

	public static Response create(CloseableHttpResponse response) {
		Assert.isTrue(response == null, "response不能为空!");
		return new Response(response);
	}

	@SuppressWarnings("unchecked")
	public <T> T getObject(Class<T> c) {
		if (c.isAssignableFrom(List.class)) {
			throw new IllegalArgumentException("数组类型请使用getArray方法!");
		}
		
		if (c.isAssignableFrom(String.class)) {
			return (T) convertToSTring(getResponse());
		} else if (c.isAssignableFrom(byte[].class)) {
			return (T) convertToByteArray(getResponse());
		}

		// JSON.parseObject(convertToSTring(getResponse()), new TypeR, features)
		// JSON.parseObject(convertToSTring(getResponse()), new
		// TypeReference<T>, features)

		return JSON.parseObject(convertToSTring(getResponse()), c);
	}

	public <T> T getObject(TypeReference<T> type) {
		return JSON.parseObject(convertToSTring(getResponse()), type);
	}

	public <T> T getObject(Type type) {
		return JSON.parseObject(convertToSTring(getResponse()), type);
	}

	public <T> List<T> getArray(Class<T> c) {
		return JSON.parseArray(convertToSTring(getResponse()), c);
	}

	public String toString() {
		return convertToSTring(getResponse());
	}

	public byte[] toByteArray() {
		return convertToByteArray(getResponse());
	}

	private static byte[] convertToByteArray(CloseableHttpResponse response) {
		try {
			return EntityUtils.toByteArray(response.getEntity());
		} catch (IOException e) {
			throw new RuntimeException(e);
		}
	}

	private static String convertToSTring(CloseableHttpResponse response) {
		try {
			return EntityUtils.toString(response.getEntity(), Charsets.UTF_8);
		} catch (ParseException | IOException e) {
			throw new RuntimeException(e);
		}
	}

}
